package com.ruoyi.common.utils;

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.Units;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;

public class SignImageWriteHandler implements CellWriteHandler {
    
    private static final Logger log = LoggerFactory.getLogger(SignImageWriteHandler.class);

    private Map<String, byte[]> imageMap;
    private int imageWidth;
    private int imageHeight;
    private int pixelConversionFactor;

    public SignImageWriteHandler(Map<String, byte[]> imageMap) {
        this(imageMap, 60,60, 32);
    }

    public SignImageWriteHandler(Map<String, byte[]> imageMap, int imageWidth,int imageHeight, int pixelConversionFactor) {
        this.imageMap = imageMap;
        this.imageWidth = imageWidth;
        this.imageHeight = imageHeight;
        this.pixelConversionFactor = pixelConversionFactor;
    }

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                       WriteCellData<?> cellData, Cell cell, Head head,
                                       Integer relativeRowIndex, Boolean isHead) {
        if (!isHead && cellData.getType() == CellDataTypeEnum.STRING && imageMap.containsKey(cellData.getStringValue())) {
            log.debug("Converting cell to EMPTY for placeholder: {}", cellData.getStringValue());
            cellData.setType(CellDataTypeEnum.EMPTY); // 清空文本，防止显示{}
        }
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 List<WriteCellData<?>> cellDataList, Cell cell, Head head,
                                 Integer relativeRowIndex, Boolean isHead) {
        if (CollectionUtils.isEmpty(cellDataList)) {
            log.debug("Skipping - isHead: {}, cellDataList empty: {}", isHead, CollectionUtils.isEmpty(cellDataList));
            return;
        }
        WriteCellData<?> cellData = cellDataList.get(0);
        log.debug("Processing1 cell in afterCellDataConverted - Value: {}, Type: {}", cellData.getStringValue(), cellData.getType());
        log.debug("Processing2 cell dispose - Sheet: {}, Row: {}, Column: {}, IsHead: {}",
                  writeSheetHolder.getSheetName(), relativeRowIndex, 
                  cell.getColumnIndex(), isHead);

        if (isHead || CollectionUtils.isEmpty(cellDataList)) {
            log.debug("Skipping - isHead: {}, cellDataList empty: {}", isHead, CollectionUtils.isEmpty(cellDataList));
            return;
        }


        log.debug("Cell data type: {}, string value: {}", cellData.getType(), cellData.getStringValue());
        
        if (cellData.getType() != CellDataTypeEnum.EMPTY) {
            log.debug("Skipping - cell data type is not EMPTY");
            return;
        }

        String placeholder = cellData.getStringValue();
        log.debug("Checking placeholder: {} in imageMap: {}", placeholder, imageMap.containsKey(placeholder));
        
        if (!imageMap.containsKey(placeholder)) {
            log.debug("Skipping - placeholder {} not found in imageMap", placeholder);
            return;
        }

        byte[] imageBytes = imageMap.get(placeholder);
        log.debug("Found image bytes for placeholder: {}, length: {}", placeholder, imageBytes != null ? imageBytes.length : 0);
        insertImage(cell.getSheet(), cell, imageBytes);
    }

    private void insertImage(Sheet sheet, Cell cell, byte[] imageBytes) {
        log.debug("Inserting image into sheet: {}, cell row: {}, column: {}", 
                  sheet.getSheetName(), cell.getRowIndex(), cell.getColumnIndex());
        
        Drawing<?> drawing = sheet.getDrawingPatriarch();
        if (drawing == null) {
            log.debug("Creating new drawing patriarch");
            drawing = sheet.createDrawingPatriarch();
        } else {
            log.debug("Using existing drawing patriarch");
        }

        if (imageBytes == null || imageBytes.length == 0) {
            log.warn("Image bytes are null or empty, skipping image insertion");
            return;
        }
        
        int pictureIndex = sheet.getWorkbook().addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
        log.debug("Added picture to workbook with index: {}", pictureIndex);
        
        CreationHelper helper = sheet.getWorkbook().getCreationHelper();
        ClientAnchor anchor = helper.createClientAnchor();

        int columnIndex = cell.getColumnIndex();
        int rowIndex = cell.getRowIndex();
        anchor.setCol1(columnIndex);
        anchor.setCol2(columnIndex);
        anchor.setRow1(rowIndex);
        anchor.setRow2(rowIndex);
        anchor.setDx1(Units.pixelToEMU(1));
        anchor.setDx2(Units.pixelToEMU(imageWidth));
        anchor.setDy1(Units.pixelToEMU(1));
        anchor.setDy2(Units.pixelToEMU(imageHeight));
        anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);

        drawing.createPicture(anchor, pictureIndex);
        log.debug("Created picture in sheet: {}, at row: {}, column: {}", 
                  sheet.getSheetName(), rowIndex, columnIndex);
        //sheet.setColumnWidth(columnIndex, imageWidth * pixelConversionFactor);
    }
}
